<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-button type="primary" :icon="Plus" @click="addBtnTrademark"
          >添加</el-button
        >
      </div>
    </template>
    <el-table
      v-loading="loading"
      :data="trademarkList"
      border
      style="width: 100%"
    >
      <el-table-column type="index" align="center" label="序号" width="80" />
      <el-table-column prop="tmName" label="品牌名称" width="180" />
      <el-table-column label="品牌LOGO">
        <template v-slot="{ row }">
          <img :src="row.logoUrl" style="width: 80px; height: 80px" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button
            title="修改"
            type="warning"
            size="small"
            :icon="Edit"
            @click="editTrademark(row)"
          />
          <el-button
            title="删除"
            type="danger"
            size="small"
            :icon="Delete"
            @click="btnDelete(row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器组件 -->
    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9, 12]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="prev, pager, next, jumper,->,sizes,total "
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 添加/修改品牌对话框效果 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="`${trademark.id ? '修改' : '添加'}品牌`"
    >
      <el-form
        :model="trademark"
        style="width: 80%"
        label-width="100px"
        :rules="rules"
        ref="ruleFormRef"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="trademark.tmName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${BASE_URL}/admin/product/upload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademark.logoUrl"
              :src="trademark.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>

            <template #tip>
              <div class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="saveOrUpdate(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: 'Trademark',
}
</script>

<script lang="ts" setup>
import { onMounted, ref, reactive } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { Plus, Delete, Edit } from '@element-plus/icons-vue'
import {
  reqGetTrademarkListData,
  reqSaveTrademarkInfo,
  reqUpdateTrademarkInfo,
  reqDeleteTrademarkInfo,
} from '@/api/product/trademark'
import type {
  TrademarkListModel,
  TrademarkModel,
} from '@/api/product/model/trademarkModel'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadProps } from 'element-plus'

const currentPage = ref<number>(1)
const pageSize = ref<number>(3)
const total = ref<number>(0)
const trademarkList = ref<TrademarkListModel>([])
const loading = ref<boolean>(true)

//分页器组件的相关参数
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const BASE_URL = import.meta.env.VITE_API_URL

// 添加/修改品牌对话框的相关参数
const dialogFormVisible = ref(false)
const initTrademark = () => ({ tmName: '', logoUrl: '' })
const trademark = reactive<TrademarkModel>(initTrademark())

//封装的品牌列表获取函数
const getTrademarkListData = async () => {
  loading.value = true
  const result = await reqGetTrademarkListData(
    currentPage.value,
    pageSize.value
  )
  trademarkList.value = result.records
  total.value = result.total
  loading.value = false
}
//组件挂载时获取品牌列表
onMounted(() => {
  getTrademarkListData()
})

//分页相关的两个事件
//1、更改每页显示条数触发的函数
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  pageSize.value = val
  currentPage.value = 1
  getTrademarkListData()
}

//2、点击页码触发的函数
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  currentPage.value = val
  getTrademarkListData()
}

//3、点击添加品牌按钮的事件函数
const addBtnTrademark = () => {
  dialogFormVisible.value = true
  Object.assign(trademark, initTrademark())
  // delete trademark.id
  trademark.id = undefined
  // 清除之前的那些校验规则
  ruleFormRef.value?.clearValidate()
}

//添加/修改品牌的输入校验规则
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: '品牌名称不能为空，请输入', trigger: 'blur' },
    {
      min: 2,
      max: 6,
      message: '请输入2到6位以内的品牌名称！',
      trigger: 'blur',
    },
  ],
  logoUrl: [{ required: true, message: '请上传图片！', trigger: 'blur' }],
})

//4、添加或更新品牌确定后的操作
const saveOrUpdate = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      //提交新增品牌的事件函数
      if (trademark.id) {
        const result = await reqUpdateTrademarkInfo(trademark)
      } else {
        currentPage.value = 1
        const result = await reqSaveTrademarkInfo(trademark)
      }
      ElMessage({
        message: '操作品牌成功',
        type: 'success',
      })
      dialogFormVisible.value = false
      getTrademarkListData()
    } else {
      console.log('error submit!', fields)
    }
  })
}

//5、品牌图片上传的前期格式审核
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const imgType = ['image/jpeg', 'image/jpg', 'image/png']
  if (!imgType.includes(rawFile.type)) {
    ElMessage.error('请上传jpeg/jpg/png格式的图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片的大小不能超过2MB!')
    return false
  }
  return true
}

//6、上传品牌图片成功后的操作
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  trademark.logoUrl = response.data
  // 清除之前的图片校验规则
  ruleFormRef.value?.clearValidate(["logoUrl"])
}

//7、点击编辑按钮的事件函数
const editTrademark = (row: TrademarkModel) => {
  dialogFormVisible.value = true
  Object.assign(trademark, row)
  // 清除之前的那些校验规则
  ruleFormRef.value?.clearValidate()
}

//8、点击删除按钮的消息弹出框效果及事件处理
const btnDelete = (trademark: TrademarkModel) => {
  ElMessageBox.confirm(`确定删除${trademark.tmName}这个品牌吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      await reqDeleteTrademarkInfo(trademark.id as number)
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      getTrademarkListData()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
